import Utils from './index.js'

const SIGN_REGEXP = /([yMdhsm])(\1*)/g
const DEFAULT_PATTERN = 'yyyy-MM-dd'

function padding(s, len) {
  const leng = len - (s + '').length
  for (let i = 0; i < leng; i++) { s = '0' + s }
  return s
}

const utils = {

  /**
   * 日期转字符串
   * @param {Date} date 转换的日期
   * @param {Sting} pattern 时间格式 'eg:yy/MM/dd hh:mm:ss' 注意月是大写
   * @returns {Sting}
   */
  dateToStr(date, pattern) {
    if (!date) {
      return
    }
    pattern = pattern || DEFAULT_PATTERN
    return pattern.replace(SIGN_REGEXP, function($0) {
      switch ($0.charAt(0)) {
        case 'y': return padding(date.getFullYear(), $0.length)
        case 'M': return padding(date.getMonth() + 1, $0.length)
        case 'd': return padding(date.getDate(), $0.length)
        case 'w': return date.getDay() + 1
        case 'h': return padding(date.getHours(), $0.length)
        case 'm': return padding(date.getMinutes(), $0.length)
        case 's': return padding(date.getSeconds(), $0.length)
        default:
          break
      }
    })
  },

  /**
   * 字符串转日期
   * @param {Sting} dateString 转换的日期字符串
   * @param {Sting} pattern 日期字符串格式 'eg:yy/MM/dd hh:mm:ss' 注意月是大写
   * @returns {Date}
   */
  strToDate(dateString, pattern) {
    const matchs1 = pattern.match(SIGN_REGEXP)
    const matchs2 = dateString.match(/(\d)+/g)
    // console.log(matchs1)
    // console.log(matchs2)
    if (matchs1.length === matchs2.length) {
      const _date = new Date(1970, 0, 1)
      for (let i = 0; i < matchs1.length; i++) {
        const _int = parseInt(matchs2[i])
        const sign = matchs1[i]
        switch (sign.charAt(0)) {
          case 'y': _date.setFullYear(_int); break
          case 'M': _date.setMonth(_int - 1); break
          case 'd': _date.setDate(_int); break
          case 'h': _date.setHours(_int); break
          case 'm': _date.setMinutes(_int); break
          case 's': _date.setSeconds(_int); break
        }
      }
      return _date
    }
    return null
  },
  /**
   * 清空对象的属性值
   * todo 增加深度遍历,对象类型判断
   * @param {(Object)} o
   * @returns {Object}
   */
  emptyObject(o) {
    for (const key in o) {
      o[key] = ''
    }
    return o
  },
  /**
   * 深度拷贝
   * @param {object} o 拷贝的对象
   * @returns {Object}
   */
  deepCopy(o) {
    if (o instanceof Array) {
      const n = []
      for (let i = 0; i < o.length; ++i) {
        n[i] = Utils.deepCopy(o[i])
      }
      return n
    } else if (o instanceof Object) {
      const n = {}
      for (const i in o) {
        n[i] = Utils.deepCopy(o[i])
      }
      return n
    } else {
      return o
    }
  },

  /**
   * 获取树结构数据的所有id
   * @param {Array} treeData 树结构数据
   * @param {String} idName id字段名
   * @returns {Array}
   */
  getTreeDataIDList(list, idName) {
    const returnList = [] // 存放结果的数组
    function childrenEach(arr) {
      for (let i = 0, len = arr.length; i < len; i++) {
        returnList.push(arr[i][idName])

        if (arr[i].children && arr[i].children.length) {
          childrenEach(arr[i].children)
        }
      }
      return returnList
    }
    return childrenEach(list)
  },
  /**
   * 查找节点元素的所有父级id(不包含自己)
   * @param {Sting/Number} key 节点id
   * @param {Array} treeData 树结构数据
   * @param {String} idName id字段名
   * @returns {Array}
   */
  getParentIdList(key, treeData, idName) {
    const list = [] // 在递归时操作的数组
    let returnList = [] // 存放结果的数组
    let depth = 0 // 定义全局层级
    function childrenEach(arr, depthN) {
      for (let j = 0, len = arr.length; j < len; j++) {
        depth = depthN // 将执行的层级赋值 到 全局层级
        list[depthN] = (arr[j][idName])
        if (arr[j][idName] === key) {
          returnList = list.slice(0, depthN) // 将目前匹配的数组，截断并保存到结果数组，
          break
        } else {
          if (arr[j].children && arr[j].children.length) {
            depth++
            childrenEach(arr[j].children, depth)
          }
        }
      }
      return returnList
    }
    return childrenEach(treeData, depth)
  },
  /**
   * 查找节点元素的所有子级id(不包含自己)
   * @param {Sting/Number} key 节点id
   * @param {Array} treeData 树结构数据
   * @param {String} idName id字段名
   * @returns {Array}
   */
  getChildrenIdList(key, treeData, idName) {
    // console.log(key)
    // console.log(treeData)

    let returnList = [] // 存放结果的数组

    function childrenEach(arr) {
      for (let j = 0, len = arr.length; j < len; j++) {
        if (arr[j][idName] === key) {
          returnList = Utils.getTreeDataIDList(arr[j].children)
          break
        } else {
          if (arr[j].children && arr[j].children.length) {
            childrenEach(arr[j].children)
          }
        }
      }
      return returnList
    }

    return childrenEach(treeData)
  },
  /**
   * 判断是否有子级,如果没有则删除children字段
   * @param {Sting/Number} key 叶子节点id
   * @param {Array} treeData 树结构数据
   * @returns {Array}
   */
  isHasChildren(list) {
    for (let i = 0, length = list.length; i < length; i++) {
      if (list[i].children && list[i].children.length) {
        Utils.isHasChildren(list[i].children)
      } else {
        delete list[i].children
      }
    }
    return list
  },

  building() {
    confirm('该功能正在努力开发中...,敬请期待Y(^_^)Y')
  },
  /**
     * 根据角色权限生成路由所需格式数据
     * @param {Array} list 后端返回的角色对应权限列表
     * return Array
    */
  dnyCreateRouter(list) {
    const returnList = []
    for (let i = 0, len = list.length; i < len; i++) {
      // 目录级
      if (list[i].menuType === 0) {
        const tempObj = {
          name: list[i].name,
          path: list[i].path,
          id: list[i].menuId,
          mark: list[i].mark,
          menuType: list[i].menuType,
          meta: { title: list[i].name, icon: list[i].icon },
          redirect: `${list[i].path}/${list[i].children[0].path}`,
          component: () => import(`@/layout`)
        }
        if (list[i].children && list[i].children.length) {
          tempObj.children = Utils.dnyCreateRouter(list[i].children)
        }
        returnList.push(tempObj)
      } else if (list[i].menuType === 1) { // 菜单级
        const tempObj = {
          name: list[i].name,
          path: list[i].path,
          id: list[i].menuId,
          mark: list[i].mark,
          menuType: list[i].menuType,
          meta: { title: list[i].name, mark: list[i].mark },
          component: () => import(`@/views${list[i].component}`)
        }
        if (list[i].children && list[i].children.length) {
          tempObj.children = Utils.dnyCreateRouter(list[i].children)
        }
        returnList.push(tempObj)
      }
      // else if (list[i].menuType === 2) { // 按钮级
      //   const tempObj = {
      //     name: list[i].name,
      //     path: list[i].path,
      //     id: list[i].menuId,
      //     mark: list[i].mark,
      //     menuType: list[i].menuType,
      //     hidden: true,
      //     meta: { title: list[i].name, mark: list[i].mark }
      //   }
      //   if (list[i].children && list[i].children.length) {
      //     tempObj.children = Utils.dnyCreateRouter(list[i].children)
      //   }
      //   returnList.push(tempObj)
      // }
    }
    // console.log(returnList);
    return returnList
  },
  /**
     * 查找一个数组中最大的排序
     * @param {Array} list 查找的数组
     * @param {String} sortName 排序字段名
     * return Number
    */
  getMaxSort(list, sortName) {
    let maxSort = 0
    for (let i = 0, len = list.length; i < len; i++) {
      if (list[i][sortName] > maxSort) {
        maxSort = list[i][sortName]
      }
    }
    return maxSort + 1
  }
}

export default utils

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}
